import { defineComponent, reactive, ref } from 'vue'
import { NForm, NButton, NButtonGroup, NInput } from 'naive-ui'

import { io } from 'socket.io-client'

export default defineComponent({
  name: 'AppWs',
  setup() {
    const ws = io('ws://localhost')
    const message = ref<string>('')
    const list = reactive<string[]>([])

    ws.on('pull', (message: string) => {
      list.push(message)
    })

    function sendMessage() {
      ws.emit('send', message.value)
    }

    return {
      sendMessage,
      message,
      list
    }
  },
  render() {
    return (
      <section>
        <h1>WebSocket</h1>
        <NForm>
          <NInput v-model:value={this.message} />
          <NButtonGroup>
            <NButton onClick={this.sendMessage} type='primary'>
              发送
            </NButton>
          </NButtonGroup>
          <ul>
            {this.list.map((item, k) => (
              <li key={k}>{item}</li>
            ))}
          </ul>
        </NForm>
      </section>
    )
  }
})
